import 'dart:convert';

import 'package:ac_app_flutter/config/app_config.dart';
import 'package:ac_app_flutter/config/hash_server_domain_config.dart';
import 'package:ac_app_flutter/config/server_pakcage.dart';
import 'package:ac_app_flutter/config/shell_config.dart';
import 'package:ac_app_flutter/metadata/cache_name.dart';
import 'package:ac_base_package/ac_base/util/ai_json.dart';
import 'package:ac_base_package/performance/manager/logger_kit_manager.dart';
import 'package:ac_app_flutter/protocol/app/login/get_domain_by_group_protocol.dart';
import 'package:ac_app_flutter/service/app_service.dart';
import 'package:ac_app_flutter/service/login_verify_service.dart';
import 'package:ac_app_flutter/utils/ac_ping_util.dart';
import 'package:ac_app_flutter/utils/common_util.dart';
import 'package:ac_base_package/ac_base/ac_config.dart';
import 'package:ac_base_package/ac_base/util/ac_logger.dart';
import 'package:dz_game/package/config/package_config.dart';
import 'package:dz_game/package/dzgame_package.dart';
import '../bean/protocol/site_model.dart';
import '../metadata/report_tags.dart';
import '../protocol/app/login/get_ip_country_protocol.dart';
import '../protocol/hash/get_hash_site_by_id_protocol.dart';

class AppServerDomainConfig extends AcConfig {
  /// 服务器时间(毫秒)，有AC的接口请求成功才会更新
  num serverTime = 0;

  final HashServerDomainConfig _hashConfig = HashServerDomainConfig();

  @override
  Future<void> beforeApp() async {
    // 切换网络层
    _httpEvn = HttpEvn.dev;
    // _httpEvn = HttpEvn.pre;
    // _initLiveServerUrlMap();
  }

  @override
  Future<void> delayInit() async {}

  @override
  void dispose() {}

  static const KEY_CACHE_IMG = 'domain_img';

  Future<void> init() async {
    try {
      await initApp();
    } catch (e, s) {
      print(s);
    }
  }

  @override
  Future<void> initApp() async {
    await setMainUrlList();
  }

  //当前选中域名
  List<String> get nativeUrls {
    if (isPre) {
      return NativeUrlsPakageInfo.nativeUrls['pre'] ?? [];
    }
    if (isUat) {
      return NativeUrlsPakageInfo.nativeUrls['uat'] ?? [];
    }
    return NativeUrlsPakageInfo.nativeUrls['dev'] ?? [];
  }

  String webSizeDomain = '';

  bool _isLoading = false;

  bool get hasServerUrlList => mainUrl.isNotEmpty || acIsNotEmpty(cache.getStringList(CacheName.serverUrlList));

  Future<void> setMainUrlList() async {
    //如果记载完还是空，那么设置为img
    // 设置地址配置
    _reloadServerUrlMap();
    // 查询接口是否启动加密

    try {
      onGetWebMainUrlInfo();
    } catch (e, s) {
      print(s);
    }
    // 如果AC主域名存在
    // 去获取hash站点信息
    // 去获取APP业务分组配置信息
    if (isHasMainUrl) {
      if (ShellConfig.ins.isHashGame) {
        await _hashConfig.getHashDomainUrl();
      } else {
        _hashConfig.getHashDomainUrl();
      }
    }

    if (!variableConfig.hasVisitorId) {
      await variableConfig.updateVisitorApply();
    } else {
      variableConfig.updateVisitorApply();
    }
    _isLoading = false;
    // kitLog(tag: LogTag.loginCheckLog, message: '_setUrlList-mainUrlList=${mainUrlList.toString()}, mainUrl=$_mainUrl');
  }

  // 清空本地缓存数据
  void cleanCacheMainUrl() {
    cache.removeValue(CacheName.serverUrlList);
    // mainUrlList.clear();
    // mainUrl = '';
    _hashConfig.cleanCacheMainUrl();
  }

  void _reloadServerUrlMap() {
    _scheme = '';
    _host = '';
    _serverUrlMap.clear();

    final map = urlSuffixMap.map((key, suffixList) => MapEntry(key, _url(key, isNative ? suffixList.last : suffixList.first)));
    _serverUrlMap.addAll(map);
  }

  String _url(String key, String suffix) {
    if (key == 'imageServer') {
      return '$scheme://$imgHost';
    }
    if (key == 'ws') {
      return dzgamePackage.config.domainConfig.imUrl;
    }
    return '$scheme://$host$suffix';
  }

  String get wsUrl => '${scheme == 'https' ? 'wss' : 'ws'}://$host';

  // Web站点域名 - 分享拼接用
  String _webMainUrl = '';

  String get webMainUrl => _webMainUrl;
  final _webMainList = <String>[];

  Future<void> onGetWebMainUrlInfo() async {
    if (!DomainPakageInfo.targetDomain.startsWith('@@') && DomainPakageInfo.targetDomain.length > 10) {
      _webMainList.clear();
      _webMainList.add(DomainPakageInfo.targetDomain);
      _webMainUrl = DomainPakageInfo.targetDomain;
      return;
    } else {
      final cacheUrls = cache.getStringList(CacheName.serverWebUrlList);
      if (cacheUrls.isNotEmpty) {
        _webMainList.clear();
        //如果打包机指定域名，那么优先这个域名
        _webMainList.addAll(cacheUrls);
      }
      final list = await Future.wait<String>(_webMainList.map((e) => AcPingUtil.httpPingUri(e, terminal: 2)).toList());
      final url = list.firstWhere((element) => element.isNotEmpty, orElse: () => '');
      _webMainUrl = url;
      if (_webMainUrl.isNotEmpty) {
        return;
      }
    }
    List<String> domainList = dzgamePackage.config.domainConfig.apiMainUrls.fold([], (previousValue, element) => previousValue..addAll(element.domainList));
    cache.setStringList(CacheName.serverWebUrlList, domainList);
    _webMainList.clear();
    _webMainList.addAll(domainList);
    // 获取配置可用地址
    final list = await Future.wait<String>(_webMainList.map((e) => AcPingUtil.httpPingUri(e, terminal: 2)).toList());
    final url = list.firstWhere((element) => element.isNotEmpty, orElse: () => '');
    // 服务器存在可用域名
    if (url.isNotEmpty) {
      _webMainUrl = url;
    } else {
      _webMainUrl = mainUrl;
    }
  }

  /// 站点主URL
  String get mainUrl => dzgamePackage.config.domainConfig.mainUrl;

  bool get isHasMainUrl => mainUrl.isNotEmpty;
  // final mainUrlList = <String>[];

  /// 站点协议
  String _scheme = '';
  String get scheme {
    if (_scheme.isNotEmpty) return _scheme;

    if (mainUrl.isNotEmpty && _scheme.isEmpty) {
      final uri = Uri.parse(mainUrl);
      _scheme = uri.scheme;
      acLog.app('uri.scheme=${uri.scheme}');
    } else {
      _scheme = 'http';
    }
    return _scheme;
  }

  String _host = '';
  String get host {
    if (mainUrl.isNotEmpty && _host.isEmpty) {
      final uri = Uri.parse(mainUrl);
      _host = uri.host;
      acLog.app('uri.host=${uri.host}');
    }
    return _host;
  }

  String get imgHost {
    return dzgamePackage.config.domainConfig.imgUrl;
  }

  String get imgUrl {
    return '$scheme://$imgHost';
  }

  HttpEvn _httpEvn = HttpEvn.pre;

  HttpEvn get httpEvn {
    if (acIsNotEmpty(EnvPakageInfo.branch) && !EnvPakageInfo.branch.startsWith('@@')) {
      switch (EnvPakageInfo.branch) {
        case 'beta':
          return HttpEvn.uat;
        case 'dev':
          return HttpEvn.dev;
        case 'main':
          return HttpEvn.pre;
      }
    }
    return _httpEvn;
  }

  bool get isNative => httpEvn == HttpEvn.native;
  bool get isDev => httpEvn == HttpEvn.dev;
  bool get isUat => httpEvn == HttpEvn.uat;
  bool get isPre => httpEvn == HttpEvn.pre;

  /// 域名后缀 key-[dev/uat/pre, native]
  Map<String, List<String>> get urlSuffixMap => {
        'gateway': ['/gateway', ''],
        'userManager': ['/userManager', ':16115'],
        'sitePost': ['/site', ':16212'],
        'userServer': ['/user', ':16110'],
        'gameServer': ['/applet', ':16108'],
        'betServer': ['/orderUser', ':16203'],
        'walletServer': ['/wallet', ':16109'],
        'imageServer': ['', ':16203'],
        'uploadServer': ['/user', ':16110'],
        'activityServer': ['/activity', ':16102'],
        'fundsServer': ['/finance', ':16107'],
        'awardServer': ['/award', ':16205'],
        'baseUrl': ['', ''],
        'msgServer': ['/message', ':16105'],
        'analyzeServer': ['/analyze', ':16206'],
        'im': ['/im', ':16111'],
        'miracleServer': ['/miracle/api/c/gate', ':16204/api/c/gate'],
        'internalServer': ['/vcmanage', ':19000'],
        'ws': ['/ws', ':16105'],
        'customerService': ['/kefu/home', ':/kefu/home'],
        'award': ['/award', ':16205'],
        'acmultilang': ['/acmultilang', ':16209'],
        'acHash': ['/achash', ':12001'],
        'analyzeMysql': ['/analyzeMysql', ':16211'],
        'customer': ['/customer', ':16401'],
        'agentService': ['/agent', ':16208'],
        'appletCalculate': ['/appletCalculate', ':16119'],
        'userShareService': ['/userShare', ':16113'],
        'liveServer': ['/liveServer', ':16405'],
        'task': ['/task', ':16306'],
        'user': ['/user', ':16110'],
        'recommend': ['/recommend', ':16218'],
        'schedule': ['/schedule', ':16001'],
        'financeService': ['/finance', ':16107'],
        'ampScheduleService': ['/ampScheduleService', ':16204'],
        'orderDepository': ['/orderDepository', ':16202'],
      };

  /// 本地写死域名，用于请求站点域名列表
  String get _devSite => 'https://inl.appsusa.net/site';
  String get _uatSite => 'https://acinl.com/site'; //'https://web01.audiortc.com/site';
  String get _preSite => 'https://fzqwhd.com/site';

  final Map<String, String> _serverUrlMap = {};

  String get ws => _serverUrlMap['ws']!;

  String get site => isPre ? _preSite : (isUat ? _uatSite : _devSite);

  String get sitePost => _serverUrlMap['sitePost'] ?? '';

  String get msgPost => _serverUrlMap['msgServer'] ?? '';

  String get analyzePost => _serverUrlMap['analyzeServer'] ?? '';

  String get userPost => _serverUrlMap['userServer'] ?? '';

  String get gateway => _serverUrlMap['gateway'] ?? '';

  String get userManager => _serverUrlMap['userManager'] ?? '';

  String get gamePost => _serverUrlMap['gameServer'] ?? '';

  String get betPost => _serverUrlMap['betServer'] ?? '';

  String get walletPost => _serverUrlMap['walletServer'] ?? '';

  String get imagePost => _serverUrlMap['imageServer'] ?? '';

  String get uploadPost => _serverUrlMap['uploadServer'] ?? '';

  String get activityPost => _serverUrlMap['activityServer'] ?? '';

  String get fundsPost => _serverUrlMap['fundsServer'] ?? '';

  String get miraclePost => _serverUrlMap['miracleServer'] ?? '';

  String get customerPost => _serverUrlMap['customerService'] ?? '';

  String get feedbackPost => _serverUrlMap['customer'] ?? '';

  String get imPost => _serverUrlMap['im'] ?? '';

  String get awardPost => _serverUrlMap['awardServer'] ?? '';

  String get internalPost => _serverUrlMap['internalServer'] ?? '';

  String get baseUrl => _serverUrlMap['baseUrl'] ?? '';

  String get acMultiLang => _serverUrlMap['acmultilang'] ?? '';

  String get analyzeMysql => _serverUrlMap['analyzeMysql'] ?? '';

  String get agentPost => _serverUrlMap['agentService'] ?? '';

  String get acHash => _serverUrlMap['acHash'] ?? '';

  String get appletCalculate => _serverUrlMap['appletCalculate'] ?? '';

  String get userShare => _serverUrlMap['userShareService'] ?? '';

  String get liveServer => _serverUrlMap['liveServer'] ?? '';

  String get ampScheduleService => _serverUrlMap['ampScheduleService'] ?? '';

  String get taskPost => _serverUrlMap['task'] ?? '';

  String get recommendPost => _serverUrlMap['recommend'] ?? '';

  String get schedule => _serverUrlMap['schedule'] ?? '';

  String get financePost => _serverUrlMap['financeService'] ?? '';
  String get user => _serverUrlMap['user'] ?? '';

  String get orderDepository => _serverUrlMap['orderDepository'] ?? '';

  // hash 配置

  String get hashUrl => _hashConfig.hashUrl;

  bool get isHasHashUrl => hashUrl.isNotEmpty;

  String get hashHost => _hashConfig.host;

  String get hashServer => _hashConfig.hashServer;

  String get hashImagePost => _hashConfig.imagePost;

  String get tronDomain {
    if (httpEvn == HttpEvn.pre || httpEvn == HttpEvn.uat) {
      return 'https://apilist.tronscan.org/';
    }
    return 'https://shastapi.tronscan.org/';
  }

  String get tronWebDomain {
    if (httpEvn == HttpEvn.pre || httpEvn == HttpEvn.uat) {
      return 'https://tronscan.org/';
    }
    return 'https://shasta.tronscan.org/';
  }

  String get tronTransactionUrl => tronWebDomain + '#/transaction/';

  String get addressUrl => tronWebDomain + '#/address/';

  String get redirectUrl {
    if (isDev) {
      return 'https://ac-web-transfer.huosx.com/';
    } else if (isPre) {
      return 'https://ac-web-transfer.allacim.com/';
    }
    return 'https://verify.huosx.com/';
  }

  // String imgName = 'img';
  int time = 0;
}
